﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using System.Linq;
using Pakxel.Data;
using Telerik.WinControls.UI;
using System.Data.Common;

namespace Pakxel.SmartLogistic
{
    public partial class FacturaWorkBench : Telerik.WinControls.UI.RadForm
    {
        private MEDataDataContext DataContext;
        private delegate bool RuleManager(string CString);
        private Pakxel.Framework.Rules ruleToCheck;
        private RuleManager IsNumeric;

        bool EsNueva = true;
        public FacturaWorkBench()
        {
            InitializeComponent();
        }

        void SetupFacturasGrid(bool SoloSinFacturar)
        {
            if (SoloSinFacturar)
            {
                FacturasGrid.Columns.Add("T005FechaInicio", "Fecha", "T005FechaInicio");
                FacturasGrid.Columns["T005FechaInicio"].FormatInfo = new System.Globalization.CultureInfo("es-MX");
                FacturasGrid.Columns["T005FechaInicio"].FormatString = "{0:dd/MM/yyyy hh:mm tt}";
                FacturasGrid.Columns.Add("T021NoCartaPorte", "NoCartaPorte", "T021NoCartaPorte");
                FacturasGrid.Columns.Add("T021NoCartaPorteCte", "NoCartaPorteCte", "T021NoCartaPorteCte");
                FacturasGrid.Columns.Add("T011Nombre", "Cliente", "T011Nombre");
                FacturasGrid.Columns.Add("T007IdRemolque", "Remolque", "T007IdRemolque");
                FacturasGrid.Columns.Add("Origen", "Origen", "Origen");
                FacturasGrid.Columns.Add("Destino", "Destino", "Destino");
                FacturasGrid.Columns.Add("T021Subtotal", "Subtotal", "T021Subtotal");
                FacturasGrid.Columns["T021SubTotal"].FormatInfo = new System.Globalization.CultureInfo("es-MX");
                FacturasGrid.Columns["T021SubTotal"].FormatString = "{0:C}";
            }
            else
            {

            }
        }

        private void Factura_Load(object sender, EventArgs e)
        {
          WorkBenchFilter.TextBox.BackColor = Color.LightYellow;
          try
          {
            FilterSelector.SelectedIndex = 0;
            FacturasGrid.MultiSelect = true;
            DataContext = new MEDataDataContext(WorkBench.ConnectionString);
            SetupFacturasGrid(true);
            WorkBenchFilter.Text = string.Empty;
            FacturasGrid.DataSource = DataContext.GetTable<FacturasView>();
            foreach (GridViewDataColumn col in this.FacturasGrid.Columns)
            {
              col.BestFit();
            }
            // Para el No de Factura
            ruleToCheck = new Framework.Rules();
            IsNumeric += new RuleManager(ruleToCheck.IsNumeric);
          }
          catch (SystemException ex)
          {
            MainApp.WriteExceptionToLog(ex);
          }
        }

        private void FacturasGrid_SelectionChanged(object sender, EventArgs e)
        {
            double ST = 0.0;
            foreach (GridViewRowInfo Row in FacturasGrid.SelectedRows)
            {
                ST += Convert.ToDouble(Row.Cells["T021SubTotal"].Value);  
            }
            Subtotal.Text = string.Format("{0:C}",ST);
            Iva.Text = string.Format("{0:C}", ST * .016);
            Retencion.Text = string.Format("{0:C}", ST * .04);
            Total.Text = string.Format("{0:C}", ST + (ST * 0.16) - (ST * .04));
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            if (EsNueva)
            {
                if (DataContext.Connection.State != ConnectionState.Closed)
                {
                    DataContext.Connection.Close();
                    DataContext.Connection.Open();
                }
                else
                    DataContext.Connection.Open();
                using (DbTransaction transaction = DataContext.Connection.BeginTransaction(IsolationLevel.Serializable))
                {
                    DataContext.Transaction = transaction;
                    try
                    {
                        T014 Parametros = (from P in DataContext.T014s where P.T014IdParametro.Equals("FOLFAC") select P).SingleOrDefault();
                        Parametros.T014Val1 = (Convert.ToInt32(Parametros.T014Val1) + 1).ToString();
                        DataContext.SubmitChanges();
                        foreach (GridViewRowInfo Row in FacturasGrid.SelectedRows)
                        {
                            var CartaPorte = (from CP in DataContext.T021s where CP.T021NoCartaPorte.Equals(Row.Cells["T021NoCartaPorte"].Value) select CP).SingleOrDefault();
                            if (CartaPorte != null)
                            {
                              CartaPorte.T021Facturada = 'S';
                              CartaPorte.T017s.Add(new T017() { T017NoFactura = Convert.ToInt32(Parametros.T014Val1), T021NoCartaPorte = CartaPorte.T021NoCartaPorte, T017Cancelada='N',T017Fecha=DateTime.Now });
                            }
                        }
                        
                        DataContext.SubmitChanges();
                        transaction.Commit();
                        NoFactura.Text = Parametros.T014Val1;
                        FacturasGrid.DataSource = from F in DataContext.FacturasViews select F;
                        foreach (GridViewDataColumn col in this.FacturasGrid.Columns)
                        {
                            col.BestFit();
                        } 
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        MainApp.WriteExceptionToLog(ex);
                    }
                    finally
                    {
                        DataContext.Connection.Close();
                    }
                }
            }
        }

        private void tsbNvo_Click(object sender, EventArgs e)
        {
          try
          {
            WorkBenchFilter.Text = string.Empty;
            FacturasGrid.DataSource = DataContext.GetTable<FacturasView>();
            foreach (GridViewDataColumn col in this.FacturasGrid.Columns)
            {
              col.BestFit();
            }
          }
          catch (SystemException ex)
          {
            MainApp.WriteExceptionToLog(ex);
          }
          finally { EsNueva = true; }
        }

        private void WorkBenchFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (IsNumeric(WorkBenchFilter.Text))
                {
                  try
                  {
                    FacturasGrid.DataSource = DataContext.GetFacturas(Convert.ToInt32(WorkBenchFilter.Text));
                    foreach (GridViewDataColumn col in this.FacturasGrid.Columns)
                    {
                      col.BestFit();
                    }
                    if (FacturasGrid.RowCount >= 1)
                    {
                      EsNueva = false;
                    }
                  }
                  catch (SystemException ex)
                  {
                    MainApp.WriteExceptionToLog(ex);
                  }
                }
                else
                {
                  try
                  {
                    FacturasGrid.DataSource = DataContext.GetTable<FacturasView>();
                    foreach (GridViewDataColumn col in this.FacturasGrid.Columns)
                    {
                      col.BestFit();
                    }
                  }
                  catch (SystemException ey)
                  {
                    MainApp.WriteExceptionToLog(ey);
                  }
                }
            }
        }

        private void tsbEdit_Click(object sender, EventArgs e)
        {
            // Validar Rol del usuario
            // Buscar la factura a eliminar y actualizar su estatus a cancelada
            // Buscar las cartas porte que componen la factura y actualizar su estatus a no facturadas
        }
    }
}
